<!-- 校区负责人发布秒杀 -->
<template>
  <div class="main">
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="开始时间">
        <div class="block">
          <el-date-picker
            v-model="queryParams.startTime"
            type="datetime"
            placeholder="请选择开始时间"
          />
        </div>
      </el-form-item>
      <el-form-item label="结束时间">
        <div class="block">
          <el-date-picker
            v-model="queryParams.endTime"
            type="datetime"
            placeholder="请选择结束时间"
          />
        </div>
      </el-form-item>
      <el-form-item label="支付状态" prop="paymentStatus">
        <el-select
          v-model="queryParams.paymentStatus"
          placeholder="请选择支付状态"
          filterable
        >
          <el-option label="待审核" value="待审核"></el-option>
          <el-option label="已通过" value="已通过"></el-option>
          <el-option label="已拒绝" value="已拒绝"></el-option>
          <el-option label="已发布" value="已发布"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="default" @click="searchBtn()"
          >搜索</el-button
        >
        <el-button size="default" @click="resetBtn">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="middle">
      <div class="add" style="margin-left: 20px">
        <div class="button">
          <el-button type="primary" :icon="Plus" @click="handleApplySecKill()"
            >申请秒杀活动</el-button
          >
        </div>
      </div>
    </div>

    <el-empty
      description="暂无发布的活动，点击左上角申请发布秒杀活动"
      v-show="emptyShow"
    />

    <el-table
      :data="filterTableData"
      row-key="seckillId"
      style="width: 100%"
      v-show="!emptyShow"
      @selection-change="handleSelectionChange"
    >
      <!-- 主要信息：原价，秒杀价，标题，状态，课程，开始时间和结束时间 -->
      <el-table-column type="selection" />
      <el-table-column label="序号" prop="index">
        <template #default="scope">{{ scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column label="活动标题" prop="title" />
      <el-table-column label="课程名" prop="courseName" />
      <el-table-column label="总数量" prop="totalLimit" />

      <el-table-column label="原价" prop="price" />
      <el-table-column label="秒杀价" prop="seckillPrice" />
      <el-table-column
        label="开始时间"
        prop="startTime"
        :formatter="(row) => formatDate(row.startTime, 'YYYY-MM-DD HH:mm:ss')"
      />
      <el-table-column
        label="结束时间"
        prop="endTime"
        :formatter="(row) => formatDate(row.endTime, 'YYYY-MM-DD HH:mm:ss')"
      />
      <el-table-column label="状态" prop="status" />
      <el-table-column align="right">
        <template #header>
          <el-input
            v-model="search"
            size="small"
            placeholder="请输入活动标题"
          />
        </template>
        <template #default="scope">
          <el-button
            size="large"
            type="success"
            @click="handleEdit(scope.$index, scope.row)"
          >
            查看活动详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 40]"
      v-show="!emptyShow"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 具体信息显示 -->
    <el-dialog v-model="infoVisible" :modal="true" width="800px">
      <el-form :model="nowRow" :rules="rules">
        <h1 class="formTitle">{{ nowRow.formTitle }}</h1>

        <el-row v-show="!nowRow.formItemVisible">
          <el-col :span="11">
            <el-form-item label="活动标题" label-width="120px">
              <el-input
                v-model="nowRow.title"
                placeholder="请输入活动标题"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="秒杀课程" label-width="120px">
              <el-select
                v-model="nowRow.courseId"
                placeholder="请选择要发布的秒杀课程"
                filterable
              >

              <el-option :key="item.courseId" 
                :label="item.courseName" 
                :value="item.courseId" 
                v-for="item in courseList"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-show="!nowRow.formItemVisible">
          <el-col :span="11">
            <el-form-item label="原价" label-width="120px">
              <el-input-number
                v-model="nowRow.price"
                :disabled="nowRow.formItemVisible"
                :min="1"
                :precision="2"
                                style="width: 250px;"

                ><template #suffix>
                  <span>RMB</span>
                </template></el-input-number
              >
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="秒杀价" label-width="120px">
              <el-input-number
                v-model="nowRow.seckillPrice"
                :disabled="nowRow.formItemVisible"
                :min="0.01"
                :precision="2"
                style="width: 250px;"
              >
                <template #suffix>
                  <span>RMB</span>
                </template></el-input-number
              >
            </el-form-item>
          </el-col>
        </el-row>

    
        <el-row>
          <el-col :span="11">
            <el-form-item
              label="秒杀时间"
              label-width="120px"
              prop="seckillTime"
            >
              <el-input-number
                v-model="nowRow.seckillTime"
                :disabled="nowRow.formItemVisible"
                :min="1"
                :max="168"
              >
                <template #suffix>
                  <span>小时</span>
                </template>
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item
              label="校区名称"
              label-width="120px"
              prop="campusName"
            >
              <el-input
                v-model="nowRow.campusName"
                placeholder="请输入校区名"
                label-width="120"
                :disabled="nowRow.formItemVisible"

              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item
              label="创建时间"
              label-width="120px"
              v-show="nowRow.formItemVisible"
            >
              <div class="block">
                <el-date-picker
                  v-model="nowRow.createTime"
                  type="date"
                  value-format="YYYY-MM-DD HH:mm"
                  format="YYYY-MM-DD HH:mm"
                  :disabled="true"
                >
                </el-date-picker>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item
              label="更新时间"
              label-width="120px"
              v-show="nowRow.formItemVisible"
            >
              <div class="block">
                <el-date-picker
                  v-model="nowRow.updateTime"
                  type="date"
                  value-format="YYYY-MM-DD HH:mm"
                  format="YYYY-MM-DD HH:mm"
                  :disabled="true"
                >
                </el-date-picker>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item
              label="限购数量"
              label-width="120px"
            >
              <el-input-number
                v-model="nowRow.studentLimitCount"
                :disabled="nowRow.formItemVisible"
                :min="1"
                :max="10"
              />
            </el-form-item>
          </el-col>
          <el-col :span="11" v-show="!nowRow.formItemVisible">
            <el-form-item label="开始时间" label-width="120px" prop="startTime">
              <div class="block">
                <el-date-picker
                  v-model="nowRow.startTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  format="YYYY-MM-DD HH:mm"
                  :required="true"
                >
                </el-date-picker>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="11" v-show="!nowRow.formItemVisible">
            <el-form-item label="总数量" label-width="120px">
              <div class="block">
                <el-input-number v-model="nowRow.totalLimit" :disabled="nowRow.formItemVisible" :min="1"/>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item
              label="已售数量"
              label-width="120px"
              prop="soldCount"
              v-show="nowRow.formItemVisible"
            >
              <el-input-number v-model="nowRow.soldCount" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              label="拒绝原因"
              label-width="120px"
              prop="rejectReason"
              v-show="nowRow.formItemVisible"
            >
            <el-input
                v-model="nowRow.rejectReason"
                style="width: 580px"
                :autosize="{ minRows: 1, maxRows: 4 }"
                type="textarea"
            />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCanle">取消</el-button>
          <el-button type="primary" @click="handleConfirm"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { formatDate, formatDateUTC } from "@/utils/dateFormat";
import { getAllSecKill ,insertSecKill,queryCampusNameWhenSecKill,queryAllCourseByCampusId} from "@/api/secKill";
import {
  Calendar,
  Search,
  Edit,
  Plus,
  Delete,
  Phone,
  Warning,
} from "@element-plus/icons-vue";

const user = {
  userId: 4,
  userAcc: "campus1",
  userPwd: "e10adc3949ba59abbe56e057f20f883e",
  userName: "王校区",
  userSex: "女",
  userPhone: "13800138003",
  userEmail: "campus1@example.com",
  userStatus: "正常",
  lastLoginTime: "2025-05-17 19:38:01",
  createTime: "2025-05-17 19:38:01",
  userNote: "北京校区负责人",
  campusId:1
};

const emptyShow = ref(false);
const infoVisible = ref(false);
const rules = ref({
  startTime: [
    { required: true, message: '开始时间不能为空', trigger: 'blur' },
    { type: 'date', message: '请选择有效的日期时间', trigger: 'change' }
  ],
});
//分页组件
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref();
const courseList = ref([]);

//表单参数
var formData = ref({
  seckillId: 0,
  title: "",
  courseId: null,
  price: 0,
  seckillPrice: 0,
  startTime: "",
  seckillTime: 0, //秒杀时间（小时）
  endTime: "",
  studentLimitCount: 0,
  soldCount: 0,
  campusId: 0,
  status: "",
  rejectReason: "", //拒绝原因
  createTime: "",
  updateTime: "",
});
//选中的记录
const nowRow = ref({
  studentLimitCount: 0,
  totalLimit:0,
  formTitle: "",
  formItemVisible: true, //控制表单里面元素的显示
  seckillPrice: 0.01,//秒杀价
  price: 0.01,//原价
  seckillTime: 1,//秒杀时长
  title:'',
  startTime: "",
  courseId:0,
  courseName:'',
  campusName:'',//校区名
  campusId:0,//校区id
});
//查询参数
const queryParams = ref({
  seckillId: 0,
  title: "",
  courseId: null,
  price: 0,
  seckillPrice: 0,
  startTime: "",
  seckillTime: 0, //秒杀时间（小时）
  endTime: "",
  studentLimitCount:'',
  soldCount: 0,
  campusId: 0,
  status: "",
  rejectReason: "", //拒绝原因
  createTime: "",
  updateTime: "",
});
//重置查询表单
function resetBtn() {
  queryParams.value = {
    seckillId: 0,
    title: "",
    courseId: "",
    price: 0,
    seckillPrice: 0,
    startTime: "",
    seckillTime: 0, //秒杀时间（小时）
    endTime: "",
    studentLimitCount: 0,
    soldCount: 0,
    campusId: 0,
    totalLimit:0,//总数量
    status: "",
    rejectReason: "", //拒绝原因
    createTime: "",
    updateTime: "",
  };
}
//搜索
function searchBtn() {
  console.log("搜索");
  console.log(queryParams.value);
}
//申请秒杀活动
async function handleApplySecKill() {
  infoVisible.value = true;
  visible.value=true;
  nowRow.value = {
    studentLimitCount: 0,
    totalLimit:0,
    formTitle: "",
    formItemVisible: true, //控制表单里面元素的显示
    seckillPrice: 0.01,//秒杀价
    price: 0.01,//原价
    seckillTime: 1,//秒杀时长
    title:'',
    startTime: "",
    courseId:null,
    courseName:'',
    campusName:'',//校区名
    campusId:0,//校区id
  };
  nowRow.value.formItemVisible = false;

  const params={
    campusId:user.campusId
  }

  const res=await queryCampusNameWhenSecKill(params);
  
    const response=await queryAllCourseByCampusId(params);
    courseList.value=response.data.courseList
    console.log(courseList.value);

  nowRow.value.campusName=res.data.campusName;  
  nowRow.value.formTitle = "申请秒杀活动";
 
}

const tableData = ref([]);
const search = ref("");

const filterTableData = computed(() =>
  tableData.value.filter(
    (data) =>
      !search.value ||
      data.title.toLowerCase().includes(search.value.toLowerCase())
  )
);
// 选中某一列
function handleSelectionChange(selected) {}
//修改每页的页码
const handleSizeChange = (val) => {
  pageSize.value = val;
  console.log("每页页数：" + val);
    hanldePage();

};
//修改当前页
const handleCurrentChange = (val) => {
  currentPage.value = val;
  console.log("当前页" + val);
    hanldePage();

};
//生命周期
onMounted(async () => {
  hanldePage();
});
//分页查询
async function hanldePage() {

  const params = {
    pageSize: pageSize.value,
    currentPage: currentPage.value,
    userId: user.userId,
  };

  // 查找校区负责人ID对应的合同
  try {
    const response = await getAllSecKill(params);

    console.log(response);
    
    total.value = response.data.allSecKill.total;
    if (response.code === 200) {
      tableData.value = response.data.allSecKill.records || []; // 更新表格数据
      emptyShow.value = tableData.value.length === 0; // 控制空状态显示
      console.log("获取申请秒杀活动列表成功:", tableData.value);
    } else {
      ElMessage.error(response.message || "获取申请秒杀活动列表失败");
    }
  } catch (error) {
    console.error("获取申请秒杀活动列表出错:", error);
    ElMessage.error("获取申请秒杀活动列表，请稍后重试");
  }
}
//查看秒杀活动详情
const visible=ref();//判断用户是点击申请还是查看详情————》主要是解决待审核时候，用户想更新数据
 const handleEdit = async (index, row) => {
  visible.value=false;
    infoVisible.value=true;
  nowRow.value = row;
   const params={
    campusId:user.campusId
  }

    const response=await queryAllCourseByCampusId(params);
    courseList.value=response.data.courseList

    // 找到对应课程并设置默认选中
    const selectedCourse = courseList.value.find(course => course.courseId === row.courseId);
    if (selectedCourse) {
      nowRow.value.courseId = selectedCourse.courseId;
    }
 
  if (row.status!=="待审核") {
    openSucAndWar("该申请已完成,不可修改!!",'warning');
    nowRow.value.formItemVisible = true;
  }else{
    nowRow.value.formItemVisible = false;
  }
  nowRow.value.formTitle = "秒杀活动详情";
  
  
};

//详情确认
async function handleConfirm() {
    

    if (nowRow.value.formItemVisible) {
      console.log("查看活动详情确认");
      
    }else{
      if(visible){
      console.log("修改");

      }else{
      console.log("新增");
      handleConfirmApply()

      }
    }

    
}
//确认申请
async function handleConfirmApply(){
  nowRow.value.campusId=user.campusId;
    nowRow.value.totalLimit=1;
      //判断开始时间是否为空
if (nowRow.value.startTime==""||nowRow.value.startTime==null) {
      openSucAndWar("请选择开始时间",'warning');
      return;
    }
    infoVisible.value=false;
    
    for (const course of courseList.value) {
      if (course.courseId==nowRow.value.courseId) {
        nowRow.value.courseName=course.courseName;
      }
    }
  
    console.log(nowRow.value);

  const res=await insertSecKill(nowRow.value);
  currentPage.value=1
  hanldePage();
}
//详情取消
function handleCanle() {
    infoVisible.value=false;
    
}
//消息提示(警告和成功)
const openSucAndWar = (val,type) => {
  ElMessage({
    message: val,
    type: type,
  })
}
</script>

<style>
.main {
  width: 100%;
  height: 100%;
}
.middle {
  width: 100%;
  height: 8vh;
  margin-bottom: 20px;
}

.add {
  margin-top: 15px;
  margin-left: 45px;
  width: 5%;
  height: 50%;
  float: left;
}
.formTitle {
  text-align: center;
  margin-bottom: 20px;
  font-size: 23px;
}
</style>